package com.dmai.capacity.platform.oauth.common.service.impl;

import com.dmai.capacity.platform.common.model.CapabilityVolumeChargeRule;
import com.dmai.capacity.platform.oauth.common.mapper.CapabilityVolumeChargeRuleDao;
import com.dmai.capacity.platform.oauth.common.service.ICapabilityVolumeChargeRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


@Service
public class CapabilityVolumeChargeRuleServiceImpl implements ICapabilityVolumeChargeRuleService {

    @Autowired
    private CapabilityVolumeChargeRuleDao ruleDao;

    /**
     * 保存规则
     *
     * @param rule 规则
     */
    @Override
    public int save(CapabilityVolumeChargeRule rule) {
        rule.setUpdateTime(new Date());
        if (rule.getId() == null) {
            return ruleDao.save(rule);
        } else {
            return ruleDao.update(rule);
        }
    }

    @Override
    public BigDecimal getAmount(Integer capabilityId, Integer count) {
        if (count == 0) {
            return BigDecimal.ZERO;
        }
        BigDecimal amount = BigDecimal.ZERO;
        List<CapabilityVolumeChargeRule> rules = ruleDao.findByCapability(capabilityId);
        for (CapabilityVolumeChargeRule rule : rules) {
            if (count >= rule.getLessCount() * 10000) {
                amount = rule.getPrice().multiply(BigDecimal.valueOf(count));
                break;
            }
        }
        return amount;
    }

}
